package com.cs456.TeamBobcat;

import java.io.File;
import java.util.ArrayList;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.format.Time;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.cs456.TeamBobcat.database.MyDB;

public class WhereAmI extends Activity implements OnClickListener {

	private static String TAG = "WhereAmI";

	protected Button _takeAnotherImageBtn;
	protected Button _submitImagesBtn;

	protected Button mbutton;
	protected ImageView _image;
	protected TextView _imageCount;
	protected String IMAGE_COUNT_STRING = "Number of Images: ";

	protected String _path;
	protected ArrayList<String> _imagePaths;
	protected Intent _result;
	protected ProgressDialog _progressDialog;

	protected Thread _computeResult;
	MyDB dba;
	private boolean _firstTime = true;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		Log.i(TAG, "onCreate()");

		super.onCreate(savedInstanceState);
		setContentView(R.layout.whereami);
		dba = new MyDB(this);
		dba.open();

		_takeAnotherImageBtn = (Button) findViewById(R.id.WAITakeMoreButton);
		_submitImagesBtn = (Button) findViewById(R.id.WAISubmitButton);
		_imageCount = (TextView) findViewById(R.id.WAItextView2);

		_takeAnotherImageBtn.setOnClickListener(this);
		_submitImagesBtn.setOnClickListener(this);

		_image = (ImageView) findViewById(R.id.whereami_image);

		_imagePaths = new ArrayList<String>();
		_result = new Intent(this, WhereAmIResult.class);
	}

	protected void onPostCreate(Bundle savedInstanceState) {
		super.onPostCreate(savedInstanceState);
		if (_firstTime)
			startCameraActivity();
		_firstTime = false;
	}

	public void onClick(View view) {
		Log.i(TAG, "onClick()");
		switch (view.getId()) {
		case R.id.WAISubmitButton:
			_progressDialog = ProgressDialog.show(WhereAmI.this, "",
					"Computing location. Please wait...", true);
			_result.putStringArrayListExtra("imagePaths", _imagePaths);
			_computeResult = new Thread() {
				public void run() {
					WebService server = new WebService(WhereAmI.this);
					try {
						_result.putExtra(WebService.WHERE_AM_I_RESULT_KEY,
								server.whereAmI(_imagePaths));
						_result.putExtra("pics", _imagePaths);
						WhereAmI.this.runOnUiThread(new Runnable() {
							public void run() {
								_progressDialog.dismiss();
								startActivity(_result);
								_computeResult = null;
								finish();
							}
						});
					} catch (Throwable e) {
						e.printStackTrace();
						WhereAmI.this.runOnUiThread(new Runnable() {
								public void run() {
									_progressDialog.dismiss();
									 Toast.makeText(WhereAmI.this, "A server error occured... X(", Toast.LENGTH_LONG).show();
									 finish();				
								}
							});
					}

				}
			};
			_computeResult.start();
			break;
		case R.id.WAITakeMoreButton:
			// loop back to take more photos
			startCameraActivity();
			break;
		}

	}

	protected void startCameraActivity() {
		Log.i(TAG, "startCameraActivity()");
		Time now = new Time();
		now.setToNow();

		File dir = new File(Environment.getExternalStorageDirectory()
				+ "/Pictures/TeamBobcat/");
		dir.mkdirs();
		File file = new File(dir, now.format2445() + ".jpg");
		_path = file.getPath();
		Log.d(TAG, file.getAbsolutePath());
		Uri outputFileUri = Uri.fromFile(file);

		Intent intent = new Intent(
				android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);

		startActivityForResult(intent, 0);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		Log.i(TAG, "onActivityResult resultCode: " + resultCode);
		switch (resultCode) {
		case 0:
			Log.i(TAG, "User cancelled");
			// If no pictures have been collected
			if (_imagePaths.size() == 0) {
				startActivity(new Intent(WhereAmI.this, TeamBobcat.class));
				finish();
			}
			break;

		case -1:
			onPhotoTaken();
			break;
		}
	}

	protected void onPhotoTaken() {
		Log.i(TAG, "onPhotoTaken");

		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inSampleSize = 4;
		dba.insertphotos("photo", _path);
		// dba.close();
		Bitmap bitmap = BitmapFactory.decodeFile(_path, options);

		_image.setImageBitmap(bitmap);
		_imagePaths.add(_path);
		_imageCount.setText(IMAGE_COUNT_STRING + _imagePaths.size());
	}

}